package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private RedisTemplate<String,String> redisTemplate;
    @Resource
    private AmqpTemplate amqpTemplate;
    @Resource
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public Boolean exists(String data, Integer type) {
        if (type != 1 && type != 2)
            throw new LyException(400,"请求参数有误");
        return query()
                .eq(type ==1,"username",data)
                .eq(type==2,"phone",data)
                .count() == 1;
    }

    @Override
    public void sendCode(String phone) {
        if (!RegexUtils.isPhone(phone)) {
            throw new LyException(400, "请求参数有误");
        }
        String code = RandomStringUtils.randomNumeric(6);
        redisTemplate.opsForValue().set("ly-user-" + phone, code, 5, TimeUnit.MINUTES);
        Map<String, String> msg = new HashMap<>();
        msg.put("phone", phone);
        msg.put("code", code);
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME, VERIFY_CODE_KEY, msg);
    }

    @Override
    public void register(User user, String code) {
        String cacheCode = redisTemplate.opsForValue().get("ly-user-" + user.getPhone());

        if (!StringUtils.equals(cacheCode,code))
            throw new LyException(400,"验证码错误");
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        save(user);
    }

    @Override
    public UserDTO queryUserByPhoneAndPassword(String username, String password) {

        User user = getOne(new QueryWrapper<User>().eq("username", username));
        if (user == null)
            // 用户名错误
            throw new LyException(400, "用户名或密码错误");
        if (!passwordEncoder.matches(password,user.getPassword()))
            throw new LyException(400, "用户名或密码错误");
        return new UserDTO(user);
    }


}